import {Image, StyleSheet, View, Text, TouchableOpacity, ScrollView, Dimensions} from 'react-native';
import {Stack, useRouter} from "expo-router";
import AntDesign from '@expo/vector-icons/AntDesign';
import {useEffect, useState, useCallback} from "react";
import { WebView } from "react-native-webview";
import { Asset } from 'expo-asset';
import { useFocusEffect } from '@react-navigation/native';
import { getUserAgreement } from "@/services/login"


export default function userAgreementScreen() {

    const router = useRouter();

    const [pdfUri, setPdfUri] = useState<null | string>(null);

    const loadPdf = async () => {
        try {
            // 加载资产中的PDF文件
            const asset = Asset.fromModule(require('@/assets/pdf/userAgreement.pdf'));
            await asset.downloadAsync();

            setPdfUri(asset.localUri);

        } catch (error) {
            console.error('Error loading PDF: ', error);
        }
    };

    useEffect(() => {
        getUserAgreement()
            .then(res => {
                setPdfUri(res.data.userAgreement)
                console.log('res', res);
            })
            .catch(err => {
                console.log('err', err);
            })
        // loadPdf();
    }, []);


    useFocusEffect(
        useCallback(() => {
            // 在界面聚焦时执行
            // loadPdf();
            return () => {
                // 在界面失去焦点时清理
                setPdfUri(null); // 如果需要重置状态，可以使用此代码
            };
        }, [])
    );

    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '用户协议', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#f7f7f7', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <View style={{ flex: 1 }}>
                {pdfUri ? (
                    <WebView
                        key={pdfUri}
                        style={{ flex: 1 }}
                        originWhitelist={['*']}
                        source={{ uri: pdfUri }}
                    />
                ) : (
                    <Text>加载中...</Text>
                )}
            </View>

        </View>

    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
});
